package com.example.demo.mapper;

import com.example.demo.model.Peer;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PeerMapper {
//    @Insert("INSERT INTO peer (peer_id, ip, port, last_updated, uploaded, downloaded, remaining, is_seeder, torrent_id) " +
//            "VALUES (#{peerId}, #{ip}, #{port}, #{lastUpdated}, #{uploaded}, #{downloaded}, #{remaining}, #{isSeeder}, #{torrent.id})")
//    @Options(useGeneratedKeys = true, keyProperty = "id")
//    void insertPeer(Peer peer);
//
//    @Update("UPDATE peer SET ip=#{ip}, port=#{port}, last_updated=#{lastUpdated}, " +
//            "uploaded=#{uploaded}, downloaded=#{downloaded}, remaining=#{remaining}, is_seeder=#{isSeeder} " +
//            "WHERE peer_id=#{peerId} AND torrent_id=#{torrent.id}")
//    void updatePeer(Peer peer);

    @Insert("INSERT INTO peer (peer_id, ip, port, last_updated, uploaded, downloaded, remaining, is_seeder, torrent_id, user_id) " +
            "VALUES (#{peerId}, #{ip}, #{port}, #{lastUpdated}, #{uploaded}, #{downloaded}, #{remaining}, #{isSeeder}, #{torrent.id}, #{userId})")
    void insertPeer(Peer peer);

    @Update("UPDATE peer SET ip=#{ip}, port=#{port}, last_updated=#{lastUpdated}, " +
            "uploaded=#{uploaded}, downloaded=#{downloaded}, remaining=#{remaining}, is_seeder=#{isSeeder}, user_id=#{userId} " +
            "WHERE peer_id=#{peerId} AND torrent_id=#{torrent.id}")
    void updatePeer(Peer peer);

    @Select("SELECT * FROM peer WHERE peer_id = #{peerId} AND torrent_id = #{torrentId}")
    Peer findByPeerIdAndTorrentId(@Param("peerId") String peerId, @Param("torrentId") Long torrentId);

    @Select("SELECT p.*, u.username " +
            "FROM peer p " +
            "LEFT JOIN user u ON p.user_id = u.id " +
            "WHERE p.torrent_id = #{torrentId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "peerId", column = "peer_id"),
            @Result(property = "ip", column = "ip"),
            @Result(property = "port", column = "port"),
            @Result(property = "lastUpdated", column = "last_updated"),
            @Result(property = "uploaded", column = "uploaded"),
            @Result(property = "downloaded", column = "downloaded"),
            @Result(property = "remaining", column = "remaining"),
            @Result(property = "isSeeder", column = "is_seeder"),
            @Result(property = "torrent", column = "torrent_id", one = @One(select = "com.example.demo.mapper.TorrentMapper.findById")),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "username", column = "username")
    })
    List<Peer> findSeedersByTorrentIdWithUsername(@Param("torrentId") Long torrentId);

    @Delete("DELETE FROM peer WHERE last_updated < NOW() - INTERVAL 45 MINUTE")
    void cleanupExpiredPeers();
}